package com.lark;

import atlantafx.base.theme.Dracula;
import com.lark.component.TrayComponent;
import com.lark.context.ApplicationContext;
import com.lark.layout.MainLayout;
import com.lark.utils.TaskUtil;
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;

import static com.lark.constant.AppConstant.JAVAFX_VERSION;
import static com.lark.constant.AppConstant.JAVA_VERSION;
import static com.lark.context.ApplicationContext.*;
import static com.lark.utils.InitUtil.initConfigure;

@Slf4j
public abstract class JavaFxApplication extends Application {
    static long startTime = System.currentTimeMillis();
    private Task<Object> task;

    @Override
    public void init() throws Exception {
        log.info("JavaFx {}, running on Java {}.", System.getProperty(JAVAFX_VERSION), System.getProperty(JAVA_VERSION));
        task = new Task<>() {
            @Override
            protected Object call() throws Exception {
                initConfigure();
                // 自定义加载
                initLoading();
                return "success";
            }
        };
        Thread.startVirtualThread(task);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        // 设置全局变量
        ApplicationContext.stage = primaryStage;
        Application.setUserAgentStylesheet(new Dracula().getUserAgentStylesheet());
        // 数据加载完成，关闭启动动画，展示主界面
        task.setOnSucceeded(event -> {
            StackPane root = showInitialView(primaryStage, settingModel.getWidth(), settingModel.getHeight());
            scene = primaryStage.getScene();
            root.getChildren().add(new MainLayout());
            TaskUtil.runOnce("Loading custom data...", () -> {
                afterLoading();
                return "success";
            }, success -> {
                if ("success".equals(success)) {
                    // 初始化托盘图标
                    if (settingModel.isTrayEnabled() && SystemTray.isSupported()) {
                        TrayComponent.getInstance();
                    }
                }
            }, failure -> {});
            log.info(String.format("Client initialization took: %.3f sec.", (System.currentTimeMillis() - startTime) / 1000d));
        });
    }

    /**
     * 显示初始视图
     */
    public abstract StackPane showInitialView(Stage primaryStage, double width, double height);

    /**
     * ui启动前预加载数据
     */
    public abstract void initLoading();

    /**
     * ui加载完成后的操作
     */
    public abstract void afterLoading();
}
